package cn.sycoder.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成条形码
 */
public class BarCodeUtil {
    public static String generateBarCode(String contents) throws WriterException, IOException {
        int width = 900; // 条形码宽度
        int height = 120; // 条形码高度
        String format = "png"; // 条形码图片格式

        // 定义条形码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码方式
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错等级
        hints.put(EncodeHintType.MARGIN, 2); // 边框宽度

        // 生成条形码
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, width, height, hints);

        // 将BitMatrix转换为ByteArrayOutputStream
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, format, out);

        // 将ByteArrayOutputStream转换为Base64编码格式
        byte[] bytes = out.toByteArray();
        String base64Img = Base64.encodeBase64String(bytes);

        return base64Img;
    }
}